import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

class Service implements Runnable {
	private Socket socket = null;

	private SocketInputStream sis;
	private OutputStream os;

	private Control control;
	private int id;
	
	private Servlet servlet;
	private Server server;

	public Service(Socket socket, Control control, int id, Server server) {
		System.out.println("Service, Service(Socket newSocket, Control control, int id)");

		this.socket = socket;
		try {
			sis = new SocketInputStream(socket.getInputStream());
			os = socket.getOutputStream();
		} catch(Exception e) {
			System.out.println(e.getMessage());
		}

		this.control = control;
		this.id = id;
		
		this.servlet = new Servlet(control, id);
		this.server = server;
	}

	public void closeSocket() {
		System.out.println("Service, closeSocket()");
		try {
			socket.close();
			control.log("Socket closed", id);
		} catch (IOException e) {

		}
	}

	public void run() {
		try {
			while(true) {
				if(!socket.isClosed()) {
					Request request = new Request(sis);
					control.log(request.toString()+"\n", id);

					Response response = servlet.service(request);
					control.log(response.toString(), id);

					os.write(response.getStatusLine().getBytes());
					os.write(response.getHeaders().getBytes());
					os.write(response.getBytes());
				}
			}
		} catch(Exception e) {
			//control.log(e.getMessage(), id);
		} finally {
			this.closeSocket();
			server.removeService(this);
		}
	}
}